package com.omar.labs.tamtamy;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class TamTamyGraph extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
	static final long serialVersionUID = 1L;
	private PrintWriter out = null;

	public TamTamyGraph() {
		super(); 
	}   	

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}  	

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/javascript");
		response.setCharacterEncoding("UTF-8");  
		out = response.getWriter();
		TamTamyAPI tta = new TamTamyAPI();
		String usr = request.getParameter("username");
		String pwd = request.getParameter("password");
		String logoff = request.getParameter("logoff");		
		
		if(!"".equals(logoff) && logoff!=null){			
			tta.doLogout();
			response.sendRedirect(request.getContextPath());
		}
		
		if(!"".equals(usr) && !"".equals(pwd)){		
			tta.doLogin(usr, pwd);			
			StringBuffer json = new StringBuffer();
			json.append("{\"userStats\": [");
			UserStatsList us = tta.userStats(usr, 0, 100); 		
			for(int i=0; i<us.size(); i++){
				UserStats tmp = us.get(i); 
				json.append("{\"id\": \"" + i + "\", \"generated\":\"" +  tmp.getGenerated() + "\", \"position\":\"" + tmp.getPosition() + "\"}");
				if(i+1<us.size()) json.append(",");
			}  								
			json.append("]}");			
			out.println(json.toString());
		}else{
			response.sendRedirect(request.getContextPath());
		}	
	}   	  	  

	public void init() throws ServletException {
		super.init();

	}   

	public void destory(){

	}
}




















